package com.magic.shop.config;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.magic.shop.handler.UserGroupCacheHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.context.MagicUser;
import org.ssssssss.magicapi.core.exception.MagicLoginException;
import org.ssssssss.magicapi.core.interceptor.Authorization;
import org.ssssssss.magicapi.core.interceptor.AuthorizationInterceptor;
import org.ssssssss.magicapi.core.model.Group;
import org.ssssssss.magicapi.core.servlet.MagicHttpServletRequest;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * magic 登录用户
 * 自定义用户名密码登录
 */
@Slf4j
@Component  //注入到Spring容器中
public class MagicUserAuthorizationInterceptor implements AuthorizationInterceptor {
    private static Map maUserMap=new HashMap<>();//保存ma用户缓存


    private final UserGroupCacheHandler userGroupCacheHandler;

    public MagicUserAuthorizationInterceptor(UserGroupCacheHandler userGroupCacheHandler) {

        this.userGroupCacheHandler = userGroupCacheHandler;
    }
    /**
     * 配置是否需要登录
     */
    @Override
    public boolean requireLogin() {
        return true;
    }

    /**
     * 登录后调用
     * 根据Token获取User
     */
    @Override
    public MagicUser getUserByToken(String token) throws MagicLoginException {

        if (maUserMap.get(token)!=null) {
            MagicUser magicUser=(MagicUser) maUserMap.get(token);
           // LoginUtils.currentUser.set(magicUser);--自定义版本
            return magicUser;
        }

        throw new MagicLoginException("token无效");

    }

    @Override
    public MagicUser login(String username, String password) throws MagicLoginException {
        // 根据实际情况进行修改，如查询数据库。。
        if("admin".equals(username) && "123456".equals(password)){
            // 登录成功后 构造MagicUser对象。
            StpUtil.login("1");
            //获取当前token
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            String token=tokenInfo.getTokenValue();
            MagicUser admin = new MagicUser("1", "admin", token);
            maUserMap.put(token,admin);
            return admin;
        } else if("zhangbo".equals(username) && "123456".equals(password)){
            //获取当前token
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            String token=tokenInfo.getTokenValue();
            MagicUser user = new MagicUser("2","zhang",token);
            maUserMap.put(token,user);
            return user;
        }
        throw new MagicLoginException("用户名或密码不正确");
    }



    /**
     * 是否拥有对该分组的增删改权限
     * 此方法可以不重写，则走默认的 boolean allowVisit(MagicUser magicUser, HttpServletRequest request, Authorization authorization) 方法
     */
    @Override
    public boolean allowVisit(MagicUser magicUser, MagicHttpServletRequest request, Authorization authorization, Group group) {

        log.info("=={}==={}===", JSONObject.toJSONString(authorization),JSONObject.toJSONString(group));

        if (Authorization.VIEW.toString().equals(authorization.name())) {

            Set<String> userGroupIds =     userGroupCacheHandler.getUserGroupIds(magicUser.getId());//测试用户权限--暂时写死--zhangbo用户只有test2权限


            if (userGroupIds==null||userGroupIds.isEmpty() || userGroupIds.contains(group.getId())) {
                return AuthorizationInterceptor.super.allowVisit(magicUser, request, authorization, group);
            } else {
                return false;
            }
        }else {
            return AuthorizationInterceptor.super.allowVisit(magicUser, request, authorization, group);
        }
    }
}